'use strict';

import { mealModel } from "../model/meal";
import { ServiceBase, Exceptions } from '../kalend';
import { ObjectId } from "bson";
import { usertokenService } from "./usertoken";
import { customer_accountService } from "./customer_account";

class MealService extends ServiceBase {
    constructor() {
        super(mealModel)
    }
    async query(params: any) {
        const offset = params.offset;
        const limit = params.limit;
        const token = params.token;
        if (!token) {
            throw Exceptions.notoken();
        }
        let userid = (await usertokenService.getToken(token)).userid;
        return await super.queryPagination(offset, limit, {
            filter: { userid: new ObjectId(userid) },
            populateOptions: {
                path: 'userid',
                select: 'name headimg'
            }
        });
    }
    /** 生成餐币消费记录 */
    async consumeal(vid: any, orderdata: any, type: any, source: Number) {
        let meal = orderdata.meal;
        let uid = orderdata.customerid;
        let openid = orderdata.openid;
        let filter: any = {
            status: 1
        };

        if (openid) {
            filter.openid = openid;
        }
        if (vid) {
            filter._id = vid;
        }
        else {
            filter._id = uid;
        }
        const userdata = await customer_accountService.querySingle(filter, { select: 'mealbalance' });
        let doc: any = {
            openid: openid,
            meal: meal,
            orderid: orderdata._id,
            source: source
        };
        if (vid) {
            doc.sourceuid = uid;
        }
        if (userdata) {
            doc.userid = userdata._id;
            doc.originmeal = userdata.mealbalance;
        } else {
            doc.originmeal = 0;
            doc.isaddnew = true;
            doc.remark = '订单支付成功未找到用户信息新增';
        }
        if (type === 'add') {
            doc.mealbalance = Number(doc.originmeal) + Number(meal);
        } else {
            doc.mealbalance = Number(doc.originmeal) - Number(meal);
        }
        this.create(doc);
    }
    async getMeals(userid: any) {
        let result = 0;
        let data = await mealModel.aggregate([
            {
                $match: {
                    source: 1,
                    userid: userid
                }
            },
            {
                $group: { _id: "$userid", total: { $sum: '$meal' } },

            }
        ]);
        if (data && data.length > 0) {
            result = data[0].total;
        }
        return result;
    }
}

export const mealService = new MealService();